"use client"

import { useState, useRef, useCallback } from 'react'
import { uploadAndSaveImage, StoredImage, getImagesByCategory, deleteStoredImage } from '../lib/imageStorage'
import { textStyles, fontSizes } from '../lib/fontConfig'

interface ImageUploaderProps {
  category: StoredImage['category']
  onImageSelect?: (image: StoredImage) => void
  maxImages?: number
  title?: string
}

export function ImageUploader({ 
  category, 
  onImageSelect, 
  maxImages = 10,
  title = "图片上传区域" 
}: ImageUploaderProps) {
  const [isDragging, setIsDragging] = useState(false)
  const [isUploading, setIsUploading] = useState(false)
  const [images, setImages] = useState<StoredImage[]>(() => getImagesByCategory(category))
  const [selectedImage, setSelectedImage] = useState<StoredImage | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)

  // 刷新图片列表
  const refreshImages = useCallback(() => {
    setImages(getImagesByCategory(category))
  }, [category])

  // 处理文件上传
  const handleFileUpload = async (files: FileList) => {
    if (files.length === 0) return
    
    setIsUploading(true)
    
    try {
      const uploadPromises = Array.from(files).slice(0, maxImages - images.length).map(file => {
        // 验证文件类型
        if (!file.type.startsWith('image/')) {
          throw new Error(`${file.name} 不是有效的图片文件`)
        }
        
        // 验证文件大小 (5MB限制)
        if (file.size > 5 * 1024 * 1024) {
          throw new Error(`${file.name} 文件过大，请选择小于5MB的图片`)
        }
        
        return uploadAndSaveImage(file, category)
      })
      
      const uploadedImages = await Promise.all(uploadPromises)
      refreshImages()
      
      // 如果只上传了一张图片，自动选中
      if (uploadedImages.length === 1 && onImageSelect) {
        onImageSelect(uploadedImages[0])
        setSelectedImage(uploadedImages[0])
      }
      
    } catch (error) {
      console.error('上传失败:', error)
      alert(error instanceof Error ? error.message : '上传失败，请重试')
    } finally {
      setIsUploading(false)
    }
  }

  // 拖拽事件处理
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(true)
  }

  const handleDragLeave = (e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(false)
  }

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault()
    setIsDragging(false)
    
    const files = e.dataTransfer.files
    handleFileUpload(files)
  }

  // 点击上传
  const handleClick = () => {
    fileInputRef.current?.click()
  }

  // 选择图片
  const handleImageSelect = (image: StoredImage) => {
    setSelectedImage(image)
    onImageSelect?.(image)
  }

  // 删除图片
  const handleImageDelete = (imageId: string, e: React.MouseEvent) => {
    e.stopPropagation()
    
    if (confirm('确定要删除这张图片吗？')) {
      deleteStoredImage(imageId)
      refreshImages()
      
      if (selectedImage?.id === imageId) {
        setSelectedImage(null)
      }
    }
  }

  return (
    <div className="w-full h-full flex flex-col">
      {/* 标题 */}
      <div className="mb-3">
        <h3 className={`${textStyles.sectionTitle} text-gray-800 text-center`}>{title}</h3>
        <p className={`${textStyles.caption} text-gray-600 text-center`}>
          支持拖拽上传，最多{maxImages}张图片
        </p>
      </div>

      {/* 上传区域 */}
      <div
        className={`
          relative border-2 border-dashed rounded-xl p-4 mb-3 transition-all duration-300 cursor-pointer
          ${isDragging 
            ? 'border-blue-400 bg-blue-50 scale-105' 
            : 'border-gray-300 hover:border-blue-300 hover:bg-blue-50/50'
          }
          ${isUploading ? 'pointer-events-none opacity-50' : ''}
        `}
        onDragOver={handleDragOver}
        onDragLeave={handleDragLeave}
        onDrop={handleDrop}
        onClick={handleClick}
      >
        {/* 隐藏的文件输入 */}
        <input
          ref={fileInputRef}
          type="file"
          multiple
          accept="image/*"
          className="hidden"
          onChange={(e) => e.target.files && handleFileUpload(e.target.files)}
        />

        {/* 上传提示 */}
        <div className="text-center py-6">
          {isUploading ? (
            <div className="flex flex-col items-center">
              <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mb-2"></div>
              <p className={`${textStyles.caption} text-blue-600`}>上传中...</p>
            </div>
          ) : (
            <div className="flex flex-col items-center">
              <div className={`${fontSizes.display.md} mb-2`}>📸</div>
              <p className={`${textStyles.description} text-gray-600 mb-1`}>
                拖拽图片到这里或点击上传
              </p>
              <p className={`${textStyles.caption} text-gray-500`}>
                支持 JPG、PNG、GIF 格式，单个文件不超过5MB
              </p>
            </div>
          )}
        </div>

        {/* 拖拽覆盖层 */}
        {isDragging && (
          <div className="absolute inset-0 bg-blue-100/80 rounded-xl flex items-center justify-center">
            <div className="text-center">
              <div className={`${fontSizes.display.lg} mb-2`}>📤</div>
              <p className={`${textStyles.subTitle} text-blue-600`}>松开鼠标上传图片</p>
            </div>
          </div>
        )}
      </div>

      {/* 图片列表 */}
      {images.length > 0 && (
        <div className="flex-1 min-h-0">
          <h4 className={`${textStyles.tag} text-gray-700 mb-2`}>
            已上传图片 ({images.length}/{maxImages})
          </h4>
          
          <div className="grid grid-cols-3 gap-2 max-h-40 overflow-y-auto">
            {images.map((image) => (
              <div
                key={image.id}
                className={`
                  relative group cursor-pointer rounded-lg overflow-hidden border-2 transition-all duration-200
                  ${selectedImage?.id === image.id 
                    ? 'border-blue-400 shadow-lg scale-105' 
                    : 'border-gray-200 hover:border-blue-300'
                  }
                `}
                onClick={() => handleImageSelect(image)}
              >
                {/* 图片 */}
                <img
                  src={image.url}
                  alt={image.name}
                  className="w-full h-16 object-cover"
                />
                
                {/* 删除按钮 */}
                <button
                  onClick={(e) => handleImageDelete(image.id, e)}
                  className="absolute top-1 right-1 w-5 h-5 bg-red-500 text-white rounded-full text-xs opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex items-center justify-center hover:bg-red-600"
                >
                  ×
                </button>
                
                {/* 选中指示器 */}
                {selectedImage?.id === image.id && (
                  <div className="absolute bottom-1 right-1 text-blue-500 text-sm">
                    ✓
                  </div>
                )}
                
                {/* 图片信息提示 */}
                <div className="absolute bottom-0 left-0 right-0 bg-black/50 text-white text-xs p-1 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                  {image.name.length > 15 ? image.name.substring(0, 15) + '...' : image.name}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* 空状态提示 */}
      {images.length === 0 && (
        <div className="flex-1 flex items-center justify-center">
          <div className="text-center text-gray-400">
            <div className={fontSizes.display.md}>🖼️</div>
            <p className={textStyles.caption}>还没有上传图片</p>
          </div>
        </div>
      )}
    </div>
  )
} 